package com.zsl.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.zsl.dao.BookDao;
import com.zsl.dao.OrderInfoDao;
import com.zsl.dao.OrderItemDao;
import com.zsl.dao.impl.BookDaoImpl;
import com.zsl.dao.impl.OrderInfoDaoImpl;
import com.zsl.dao.impl.OrderItemDaoImpl;
import com.zsl.model.Book;
import com.zsl.model.OrderInfo;
import com.zsl.model.OrderItem;
import com.zsl.service.OrderInfoService;
import com.zsl.util.Util;

import java.sql.SQLException;
import java.util.*;

public class OrderInfoServiceImpl implements OrderInfoService {
    OrderInfoDao orderInfoDao = new OrderInfoDaoImpl();
    BookDao bookDao = new BookDaoImpl();
    OrderItemDao orderItemDao = new OrderItemDaoImpl();

    @Override
    public Map<String, Object> opItemIntoShoppingCart(Map<String, Object> input) throws SQLException {
        Map<String, Object> result = new HashMap<>();

        String u_id = (String) input.get("u_id");
        String b_id = (String) input.get("b_id");
        //当用户强制输入0时，默认为1，不给予0的权利
        String b_num = ((String) input.get("b_num")).equals("0") ? "1" : (String) input.get("b_num");
        //用户没有拥有购物车
        if (orderInfoDao.getOrderInfoCount(new String[]{"status", "users.id"}, new String[]{"0", u_id}).equals("0")) {
            // 新建一个购物车
            List<OrderInfo> orderInfos = new ArrayList<>();
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setId(UUID.randomUUID().toString());
            orderInfo.setOrderId(Util.getNowDate());
            orderInfo.setUser_id(u_id);
            orderInfos.add(orderInfo);
            orderInfoDao.insertOrderInfo(orderInfos);
            // 并且将该物品放入购物车
            //获取该书本的信息
            Book book = bookDao.getBookById(b_id);
            //计算价格信息，并插入orderitem表
            List<OrderItem> orderItems = new ArrayList<>();
            OrderItem orderItem = new OrderItem();
            orderItem.setId(UUID.randomUUID().toString());
            orderItem.setNum(1);
            orderItem.setPrice(book.getPrice());
            orderItem.setOrderInfo_id(orderInfo.getId());
            orderItem.setBook_id(book.getId());
            orderItems.add(orderItem);
            orderItemDao.insertOrderItem(orderItems);
            // 更新orderinfo表对于订单信息（总价上升
            OrderInfo update_oi = new OrderInfo();
            List<OrderInfo> update_ois = new ArrayList<>();
            update_oi.setId(orderInfo.getId());
            update_oi.setNum(1);
            update_oi.setPrice(book.getPrice());
            update_ois.add(update_oi);
            Map<String, Object> orderinfo_result = orderInfoDao.updateOrderInfoById(update_ois, 1);
            System.out.println(orderinfo_result);
        }
        //用户拥有购物车
        else {
            // 获取用户的购物车信息
            List<OrderInfo> user_orderinfo = orderInfoDao.getOrderInfo(
                    new String[]{"status", "users.id"},
                    new String[]{"0", u_id});
            // 获取该书本的价格信息
            Book book = bookDao.getBookById(b_id);
            //TODO 判断用户的购物车是否有这本书

            // 如果没有，则插入
            if (orderItemDao.getOrderItemCount(
                    new String[]{"orderInfo_id", "book_id"},
                    new String[]{user_orderinfo.get(0).getId(), b_id}).equals("0")) {
                // 计算多个书本的价格
                Float item_price = book.getPrice() * Integer.parseInt(b_num);
                // 插入至orderitem表
                OrderItem i_orderitem = new OrderItem();
                List<OrderItem> i_orderItems = new ArrayList<>();
                i_orderitem.setId(UUID.randomUUID().toString());
                i_orderitem.setNum(Integer.parseInt(b_num));
                i_orderitem.setPrice(item_price);
                i_orderitem.setOrderInfo_id(user_orderinfo.get(0).getId());
                i_orderitem.setBook_id(book.getId());
                i_orderItems.add(i_orderitem);
                Map<String, Object> oi_ok = orderItemDao.insertOrderItem(i_orderItems);
                List<Integer> line = Util.castList(oi_ok.get("line"), Integer.class);
                //TODO 判断是否插入成功

                // 更新orderInfo(总价上升
                user_orderinfo.get(0).setNum(user_orderinfo.get(0).getNum() + 1);
                user_orderinfo.get(0).setPrice(user_orderinfo.get(0).getPrice() + i_orderitem.getPrice());
                Map<String, Object> uoi_ok = orderInfoDao.updateOrderInfoById(user_orderinfo, 1);
            }
            // 如果有，则更新
            else {
                // 获取当前书本所处订单下的条目信息
                OrderItem now_book_orderitem = orderItemDao.getOrderItem(
                        new String[]{"orderInfo_id", "book_id"}
                        , new String[]{user_orderinfo.get(0).getId(), b_id}
                ).get(0);
                // 更新条目信息
                //减去原来的条目啊价格
                user_orderinfo.get(0).setPrice(user_orderinfo.get(0).getPrice() - now_book_orderitem.getPrice());
                //更新-条目
                now_book_orderitem.setNum(Integer.parseInt(b_num));
                now_book_orderitem.setPrice(book.getPrice() * Integer.parseInt(b_num));
                List<OrderItem> orderItems = new ArrayList<>();
                orderItems.add(now_book_orderitem);
                //TODO 获取数据
                System.out.println(orderItemDao.updateOrderItemById(orderItems, 1));
                //更新-订单总价
                user_orderinfo.get(0).setPrice(user_orderinfo.get(0).getPrice() + now_book_orderitem.getPrice());
                //TODO 获取数据
                System.out.println(orderInfoDao.updateOrderInfoById(user_orderinfo, 1));
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> payShoppingCart(String u_id) throws SQLException {
        Map<String, Object> result = new HashMap<>();
        if (u_id == null || u_id.equals("")) {
            result.put("code", "0");
            result.put("msg", "用户出错");
            return result;
        }

        // 付款过程

        // 判断是否有购物车
        // 获取该用户的购物车
        List<OrderInfo> user_orderInfos = orderInfoDao.getOrderInfo(
                new String[]{"user_id", "status"},
                new String[]{u_id, "0"}
        );
        if (user_orderInfos.isEmpty()) {
            result.put("code", "0");
            result.put("msg", "购物车里面没有任何东西，无法付款");
            return result;
        }
        final OrderInfo user_orderinfo = user_orderInfos.get(0);
        // 将用户的购物车转为状态1，即代发货状态
        user_orderinfo.setStatus("1");
        orderInfoDao.updateOrderInfoById(new ArrayList<OrderInfo>() {{
            add(user_orderinfo);
        }}, 2);
        result.put("code", "1");
        result.put("msg", "付款成功");
        return result;
    }

    @Override
    public Map<String, Object> getUserOrderInfo(String u_id) throws SQLException {
        Map<String, Object> result = new HashMap<>();
        JSONArray rows = new JSONArray();
        int total = 0;
        if (u_id == null || u_id.equals("")) {
            result.put("total", "0");
            result.put("rows", rows);
            return result;
        }

        // 获取用户的订单
        List<OrderInfo> orderInfos = orderInfoDao.getOrderInfo(
                new String[]{"user_id"},
                new String[]{u_id}
        );
        if (orderInfos.isEmpty()) {
            result.put("total", "0");
            result.put("rows", rows);
            return result;
        }
        for (OrderInfo orderInfo : orderInfos) {
            Map<String, Object> orderInfo_map = new HashMap<>();
            orderInfo_map.put("orderId", orderInfo.getOrderId());
            orderInfo_map.put("info_num", orderInfo.getNum());
            orderInfo_map.put("info_price", orderInfo.getPrice());
            orderInfo_map.put("status", orderInfo.getStatus());
            orderInfo_map.put("user_id", orderInfo.getUser_id());
            orderInfo_map.put("u_name", orderInfo.getGenerate_user_name());
            rows.add(orderInfo_map);
            total++;
        }
        result.put("total", total);
        result.put("rows", rows);
        return result;
    }

    @Override
    public Map<String, Object> getAllOrderInfo() throws SQLException {
        Map<String, Object> result = new HashMap<>();
        JSONArray rows = new JSONArray();
        int total = 0;

        //获取所有订单
        List<OrderInfo> orderInfos = orderInfoDao.getOrderInfo(null, null);
        //出错处理
        if (orderInfos.isEmpty()) {
            result.put("total", "0");
            result.put("rows", rows);
            return result;
        }
        for (OrderInfo orderInfo : orderInfos) {
            Map<String, Object> orderInfo_map = new HashMap<>();
            orderInfo_map.put("orderId", orderInfo.getOrderId());
            orderInfo_map.put("info_num", orderInfo.getNum());
            orderInfo_map.put("info_price", orderInfo.getPrice());
            orderInfo_map.put("status", orderInfo.getStatus());
            orderInfo_map.put("user_id", orderInfo.getUser_id());
            orderInfo_map.put("u_name", orderInfo.getGenerate_user_name());
            rows.add(orderInfo_map);
            total++;
        }
        result.put("total", total);
        result.put("rows", rows);
        return result;
    }

    @Override
    public Map<String, Object> updateOrderInfoStatus(String orderId, String des_status) throws SQLException {
        Map<String, Object> result = new HashMap<>();
        //先通过orderId获得orderinfo_id
        List<OrderInfo> orderInfos = orderInfoDao.getOrderInfo(
                new String[]{"orderId"},
                new String[]{orderId}
        );
        if (orderInfos.isEmpty()) {
            result.put("code", "0");
            result.put("msg", "订单出错");
            result.put("line", "0");
            return result;
        }
        final OrderInfo orderInfo = orderInfos.get(0);
        //设置新的订单状态
        orderInfo.setStatus(des_status);
        //更新新的状态
        Map<String, Object> r = orderInfoDao.updateOrderInfoById(
                new ArrayList<OrderInfo>() {{
                    add(orderInfo);
                }},
                2
        );
        //判断更新情况
        List<Integer> line=Util.castList(r.get("line"),Integer.class);
        if(line.isEmpty()){
            result.put("code", "0");
            result.put("msg", "更新失败");
            result.put("line", "0");
            return result;
        }
        if(line.get(0)==0){
            result.put("code", "0");
            result.put("msg", "更新失败");
            result.put("line", "0");
            return result;
        }
        result.put("code", "1");
        result.put("msg", "更新成功");
        result.put("line", "1");
        return result;
    }


}
